import dataPreferences from '@ohos.data.preferences';
import logUtil from './logUtil';

const TAG = 'PreferencesUtil'
type ValueType = number | string | boolean | Array<number> | Array<string> | Array<boolean>;

/**
 * 数据持久化 key value
 */
class PreferencesUtil {
    preferences: dataPreferences.Preferences

    async getPreferences() {
        if (!this.preferences) {
            logUtil.info(TAG, 'getPreferences init')
            this.preferences = await dataPreferences.getPreferences(globalThis.context, 'app_preferences')
        } else {
            logUtil.info(TAG, 'getPreferences cache')
        }
        return this.preferences
    }

    /**
     * 保存数据
     * @param key 键
     * @param value 保存的数据
     */
    async put(key: string, value: ValueType) {
        let preferences = await this.getPreferences()
        logUtil.info(TAG, `put key = ${key}  value = ${value}`)
        preferences.put(key, value)
        preferences.flush()
    }

    /**
     * 获取数据
     * @param key 键
     * @param defValue 默认值
     * @return 保存的数据
     */
    async get(key: string, defValue?: ValueType) {
        let preferences = await this.getPreferences()
        let value = await preferences.get(key, defValue)
        logUtil.info(TAG, `get key = ${key}  value = ${value}  defValue = ${defValue}`)
        return value
    }
}

export default new PreferencesUtil()